<?php

/**
 * IndexController is the default controller for this application
 */
class IndexController extends BrowseControllerBase {
	/**
	 *
	 * Authentication Object
	 * @var Authentication
	 */
	protected $authentication = NULL;
	/**
	 *
	 * DealOrderDataService
	 * @var DealOrderDataService Object
	 */
	public $dealOrderDataService = null;
	/**
	 * Constructor of index
	 */
	public function __construct() {
		parent::__construct ();
		// Checking member has been logged in or not
		if ($this->authentication->getCurrentUserId () == null) {
			// Redirect to Page Not Found instead
			$url = Zend_Registry::get ( 'config' )->APPLICATION_URL;
			CommonUtils::redirect ( $url );
			return - 1;
		}
		$this->dealOrderDataService = new DealOrderDataService ();
	}
	
	/**
	 * The "index" action is the default action for all controllers -- the
	 * landing page of the site.
	 *
	 * @return void
	 */
	public function indexAction() {
		$this->personalAction ();
	
		//		// Set page name
	//		$this->setPageName('index');
	//
	//		$type = PAGE_HOME;
	//		$pageEntity = $this->userPageDataService->getByUserAndType($this->ownerId, $type);
	//		if($pageEntity)
	//		{
	//			// Set Meta Information
	//			$this->setMetaDescription($pageEntity->metaDescription);
	//			$this->setMetaKeywords($pageEntity->metaKeywords);
	//			$this->setPageTitle($pageEntity->headTitle);
	//			$pageEntity->content = htmlspecialchars_decode($pageEntity->content, ENT_QUOTES);
	//			$this->smarty->assign('pageEntity', $pageEntity);
	//		}
	//
	//		// Load 5 latest Banner
	//		$arrElement = array();
	//		$arrElement['ownerId'] = $this->ownerId;
	//		$arrElement['status'] = BannerEntity::ACTIVE;
	//		$bannerItemList = $this->bannerDataService->getItems($arrElement, NULL , 0 , 5);
	//		$this->smarty->assign('bannerItemList', $bannerItemList);
	//		$this->smarty->assign('bannerItemCount',count($bannerItemList));
	//
	//		if($this->isMobileMode == false){
	//			// Assign Smarty Content
	//			$this->assignSmartyContent('Index/index.tpl');
	//		}
	//		else {
	//			$this->assignSmartyMobileContent('Index/m_index.tpl');
	//		}
	

	}
	public function personalAction() {
		$msg = '';
		$isError = false;
		// get user_id
		$user_id = $this->authentication->getCurrentUserId ();
		// get userEntity byID
		$userDataService = new UserDataService ();
		$userEntity = $userDataService->getById ( $user_id );
		$actionForm = $this->getPost ( 'asubmit', '' );
		
		// get fullname
		$fullname = $this->getPost ( 'txtFullname', '' );
		$fullname = trim ( $fullname );
		// get gender
		$gender = $this->getPost ( 'gender', '' );
		// get birthday
		

		$birthday = $this->getPost ( 'txtBirthday', '' );
		$cbNote = $this->getPost ( 'cbNote', 0 );
		if ($actionForm != '') {
			try {
				$userEntity->fullname = $fullname;
				$userEntity->gender = $gender;
				$userEntity->birthday = $birthday;
				if ($cbNote) {
					//echo "abc";
					$authenticate = new Authentication ();
					$oldPassword = $this->getPost ( 'txtMyPass', '' );
					if ($authenticate->encryptPassword ( $oldPassword ) == $userEntity->password) {
						$newPassword = $this->getPost ( 'txtMyNewPass', '' );
						$confirmPassword = $this->getPost ( 'txtMyReNewPass', '' );
						if ($newPassword == $confirmPassword) {
							$userEntity->password = $authenticate->encryptPassword ( $newPassword );
						} else {
							$isError = true;
							$msg = "khong hop le";
						}
					
					} else {
						$isError = true;
						$msg = "error";
					}
				}
				//var_dump($userEntity);
				$res = $userDataService->update ( $userEntity );
				//var_dump($res);
				$isError = false;
				$msg = 'The record has been updated successfully';
			
			} catch ( Exception $ex ) {
				$msg = 'The item cannot update successfully. Error Code = ' . $ex->getCode ();
				$isError = true;
			}
		}
		
		$this->smarty->assign ( 'msg', $msg );
		$this->smarty->assign ( 'isError', $isError );
		$this->smarty->assign ( 'email', $userEntity->email );
		$this->smarty->assign ( 'fullname', $userEntity->fullname );
		$this->smarty->assign ( 'gender', $userEntity->gender );
		$this->smarty->assign ( 'birthday', $userEntity->birthday );
		$this->smarty->assign ( 'userEntity', $userEntity );
		$this->smarty->assign ( 'submenu', 'personal' );
		
		$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'User/Index/personal.tpl' );
		$this->smarty->display ( APPLICATION_PATH . '/Layouts/User/MainLayout.tpl' );
	}
	public function avatarAction() {
		$msg = '';
		$isError = false;
		
		// get user_id
		$user_id = $this->authentication->getCurrentUserId ();
		$userDataService = new UserDataService ();
		$actionForm = $this->getPost ( 'btnUpload', '' );
		$userEntity = $userDataService->getById ( $user_id );
		$fullname = $userEntity->fullname;
		
		if ($actionForm != '') {
			
			// upload avatar
			$picture = '';
			
			try {
				$picture = CommonUtils::uploadPictureEx ( 'UploadAvatar' );
			
		//var_dump($picture);
			} catch ( Exception $e ) {
				$msg = "Upload avatar thất bại";
				$isError = true;
			}
			if ($picture != '') {
				try {
					$userEntity->picture = $picture;
					//$userEntity->fullname = $fullname;
					//var_dump($userEntity;
					$res = $userDataService->update ( $userEntity );
					//var_dump($res);
					$isError = false;
					$msg = 'Cập nhật avatar thành công';
				} catch ( Exception $e ) {
					$isError = true;
					$msg = 'Cập nhật thất bại';
				}
			} else {
				$msg = 'Cập nhật thất bại';
				$isError = true;
			}
		}
		
		$this->smarty->assign ( 'msg', $msg );
		$this->smarty->assign ( 'isError', $isError );
		$this->smarty->assign ( 'fullname', $fullname );
		$this->smarty->assign ( 'userEntity', $userEntity );
		$this->smarty->assign ( 'submenu', 'avatar' );
		$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'User/Index/avatar.tpl' );
		$this->smarty->display ( APPLICATION_PATH . '/Layouts/User/MainLayout.tpl' );
	}
	public function myorderAction() {
		$deal_id = $this->getQuery ( 'deal_id', 0 );
		$isShow = $this->getQuery ( 'showOrder', 0 );
		$isSuccess = $this->getQuery ( 'isSuccess', 0 );
		if (($isShow) && ($deal_id)) {
			$user_id = $this->authentication->getCurrentUserId();
			$order = $this->dealOrderDataService->getItems(array('user_id' => $user_id, 'deal_id' => $deal_id));
			$this->smarty->assign( 'showOrder', 1 );
			$this->smarty->assign('order_id', $order[0]->id);
		}
		$this->smarty->assign( 'isSuccess', $isSuccess );
		//get all order of user
		$listOrders = $this->dealOrderDataService->getOrdersOfUser ( $this->authentication->getCurrentUserId () );
		$this->smarty->assign ( 'listOrders', $listOrders );
		$this->smarty->assign ( 'dealOrderEntity', new DealOrderEntity () );
		$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'User/Index/myorder.tpl' );
		$this->smarty->display ( APPLICATION_PATH . '/Layouts/User/MainLayout.tpl' );
	}
	/**
	 * About Us action Handling
	 */
	public function aboutusAction() {
		$this->setPageName ( 'about' );
		
		$type = PAGE_ABOUTUS;
		$pageEntity = $this->userPageDataService->getByUserAndType ( $this->ownerId, $type );
		if ($pageEntity) {
			// Set Meta Information
			$this->setMetaDescription ( $pageEntity->metaDescription );
			$this->setMetaKeywords ( $pageEntity->metaKeywords );
			$this->setPageTitle ( $pageEntity->headTitle );
			$pageEntity->content = htmlspecialchars_decode ( $pageEntity->content, ENT_QUOTES );
			$this->smarty->assign ( 'pageEntity', $pageEntity );
		}
		
		if ($this->isMobileMode == false) {
			// Assign Smarty Content
			$this->assignSmartyContent ( 'Index/aboutus.tpl' );
		} else {
			$this->assignSmartyMobileContent ( 'Index/m_aboutus.tpl' );
		}
	
		//$this->smarty->assign('SMARTY_CONTENT_PATH', 'template1/Index/aboutus.tpl');
	//$this->smarty->display(APPLICATION_PATH . '/Layouts/template1/MainLayout.tpl');
	}
	
	/**
	 * Contact Us Action Handling
	 */
	public function contactusAction() {
		$type = PAGE_CONTACT;
		$pageEntity = $this->userPageDataService->getByUserAndType ( $this->ownerId, $type );
		
		if ($pageEntity) {
			// Set Meta Information
			$this->setMetaDescription ( $pageEntity->metaDescription );
			$this->setMetaKeywords ( $pageEntity->metaKeywords );
			$this->setPageTitle ( $pageEntity->headTitle );
			$pageEntity->content = htmlspecialchars_decode ( $pageEntity->content, ENT_QUOTES );
			$this->smarty->assign ( 'pageEntity', $pageEntity );
		}
		
		$actionForm = $this->getPost ( 'actionForm', '' );
		
		if (! empty ( $actionForm ) && $actionForm == 'submit') {
			
			$txtFirstName = $this->getPost ( 'name', '' );
			$txtEmail = $this->getPost ( 'email', '' );
			$txtPhone = $this->getPost ( 'phone', '' );
			$subject = $this->getPost ( 'subject', '' );
			$website = $this->getPost ( 'website', '' );
			$txtContent = $this->getPost ( 'message', '' );
			
			$settingsDataService = new SettingsDataService ();
			
			$usersDataService = new UsersDataService ();
			$owner = $usersDataService->getById ( $this->ownerId );
			
			if ($owner) {
				$adminEmail = $owner->email;
				$adminName = $owner->username;
			} else {
				$adminEmail = $settingsDataService->getValue ( SETTINGS_ADMIN_EMAIL );
				$adminName = $settingsDataService->getValue ( SETTINGS_ADMIN_NAME );
			}
			
			$message = $txtContent;
			$headers = "";
			
			// SEND MAIL TO ADMINISTRATOR
			$mailer = new MyMailUtils ();
			$mailer->addFrom ( $txtEmail, $txtFirstName );
			$mailer->addTo ( $adminEmail, $adminName );
			
			$emailReplace = array ($adminName, $txtFirstName, $message, $txtPhone, $website );
			
			$contentEmal = SystemEmailDataService::getEmailContent ( SYSTEM_EMAIL_USER_CONTACT_US, $emailReplace );
			//echo "<pre>". print_r($contentEmal, true)  . "</pre>";
			//die();
			$message = $contentEmal ['message'];
			$mailer->send ( $subject, $message );
			$mailer->resetAll ();
			
			$message = 'Your request has just sent successfully';
		}
		
		$this->setPageName ( 'contact' );
		
		if ($this->isMobileMode == false) {
			// Assign Smarty Content
			$this->assignSmartyContent ( 'Index/contact.tpl' );
		} else {
			$this->assignSmartyMobileContent ( 'Index/m_contact.tpl' );
		}
	}
	
	public function viewOrderAction() {
		$order_id = $this->getQuery ( 'id', 0 );
		
		$order = $this->dealOrderDataService->getOrder ( $order_id );
		$action = $this->getPost ( 'action', '' );
		if ($action != '') {
			$dealOrderEntity = $this->dealOrderDataService->getById ( $order_id );
			if ($action == 'accept') {
				$quantity = $this->getPost ( 'quantity', 0 );
				$total_price = $order [0] ['sale_price'] * $quantity;
				$service_fee = $total_price * 5 / 100;
				
				$dealOrderEntity->quantity = $quantity;
				$dealOrderEntity->total_price = $total_price;
				$dealOrderEntity->service_fee = $service_fee;
				
				$this->dealOrderDataService->update ( $dealOrderEntity );
			} else {
				$dealOrderEntity->order_status = DealOrderEntity::CANCELLED;
				$this->dealOrderDataService->update ( $dealOrderEntity );
			
		//send mail
			}
			$url = Zend_Registry::get ( 'config' )->APPLICATION_URL .'/User/Index/myorder/deal_id/'.$dealOrderEntity->deal_id.'/showOrder/1/isSuccess/1';
			CommonUtils::redirect ( $url );
			return - 1;
		}
		$this->smarty->assign( 'isSuccess', $this->getQuery('isSuccess', 0));
		$this->smarty->assign ( 'order', $order [0] );
		$this->smarty->assign ( 'dealOrderEntity', new DealOrderEntity () );
		$this->smarty->display ( 'User/Index/viewOrder.tpl' );
	
		//$this->smarty->display ( APPLICATION_PATH . '/Layouts/User/MainLayout.tpl' );
	}

}
